package com.listviewcheckbox;

import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

public class MyAdapter extends BaseAdapter {

	private ViewHolder holder;
	private Context context;
	private String[] cons;
	private boolean flag= false;
	private Map<Integer, CheckBox> boxs= new HashMap<Integer, CheckBox>();
	private Map<Integer, Boolean> selected= new HashMap<Integer, Boolean>();
	
	public MyAdapter(Context context, String[] cons) {
		
		this.context= context;
		this.cons= cons;
		for(int i= 0;i< cons.length; i++) {
			
			selected.put(i, false);
		}
	}
	
	@Override
	public int getCount() {

		if(cons!= null) {
			
			return cons.length;	
		}
		return 0;
	}

	@Override
	public Object getItem(int position) {

		
		return cons[position];
	}

	@Override
	public long getItemId(int position) {

		
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {

		if(convertView== null) {
			
			convertView= LayoutInflater.from(context).inflate(R.layout.item, parent, false);
			holder= new ViewHolder(convertView);
			convertView.setTag(holder);
		}else {
			
			holder= (ViewHolder) convertView.getTag();
		}
		holder.name.setText(cons[position]);
		holder.box.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

				setSelected(position, isChecked);
			}
		});
		holder.box.setChecked(selected.get(position));
		boxs.put(position, holder.box);
		return convertView;
	}
	
	public void setSelected(int position, boolean flag) {
		
		selected.put(position, flag);
	}
	
	public void setAdapterCheckBoxListener(int position) {
		
		if(0< boxs.size()&& boxs.containsKey(position)) {
			
			for(int i= 0; i< boxs.size(); i++) {
				
				boxs.get(i).setVisibility(!flag? View.GONE: View.VISIBLE);
			}
			flag= !flag;
		}
	}

	class ViewHolder {
		
		TextView name= null;
		CheckBox box= null;
		
		public ViewHolder(View view) {
			
			name= (TextView) view.findViewById(R.id.name);
			box= (CheckBox) view.findViewById(R.id.box);
		}
	}
}